package com.atguigu.shardingjdbcdemo.algorithm;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;

/**
 * @author zhaojiaxu
 * @date 2021/10/21 08:58
 **/
@Slf4j
public class ComplexTableShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> complexKeysShardingValue) {
        log.info("tableNames:{}", JSON.toJSONString(collection));
        log.info("shardingValue:{}", JSON.toJSONString(complexKeysShardingValue));

        Collection<String> finalTables = new LinkedList<>();
        String tableName = "";
        if (complexKeysShardingValue.getColumnNameAndShardingValuesMap() != null && complexKeysShardingValue.getColumnNameAndShardingValuesMap().size() > 0) {
            Long cid = complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("cid").iterator().next();
            Long course_1 = 0L;
            Long course_2 = 1L;
            if ("course".equalsIgnoreCase(complexKeysShardingValue.getLogicTableName())) {
                //分表逻辑是 cid如果是偶数我们就分到 course_1这张表 如果cid是奇数我们就分到 course_2这张表
                if (course_1.equals(cid % 2)) {
                    String shardingTable = complexKeysShardingValue.getLogicTableName() + "_1";
                    tableName = shardingTable;
                } else if (course_2.equals(cid % 2)) {
                    String shardingTable = complexKeysShardingValue.getLogicTableName() + "_2";
                    tableName = shardingTable;
                }
            }

            log.info("tableName:{}", tableName);
            if (StringUtils.isNotEmpty(tableName)) {
                finalTables.add(tableName);
                return finalTables;
            }
        }


        if (complexKeysShardingValue.getColumnNameAndRangeValuesMap() != null && complexKeysShardingValue.getColumnNameAndRangeValuesMap().size() > 0) {
            ArrayList<String> rangTables = new ArrayList<>();
            rangTables.add("course_1");
            rangTables.add("course_2");
            return rangTables;
        }


        throw new UnsupportedOperationException();
    }

}

